//
//  ChallengeConfiguration.m
//  Tables
//
//  Created by mathias Muller on 8/27/08.
//  Copyright 2008 __MyCompanyName__. All rights reserved.
//

#import "ChallengeConfiguration.h"
#import "Operation.h"
#import "EasyChallenge.h"

@implementation ChallengeConfiguration
@synthesize challengeLength;

- (id)init {
	if (self = [super init]) {
		srandom([NSDate timeIntervalSinceReferenceDate]);
	}
	return self;
}

- (NSArray *) getOperations {
	NSMutableArray *o = [NSMutableArray arrayWithCapacity:self.challengeLength];
	for (int i=0; i < self.challengeLength; i++) {
		NSInteger left = 0;
		NSInteger right = 0;
		if(i-1 >= 0 && i-1 <= [o count] ) {
			Operation * previous = [o objectAtIndex:i-1];
			left = previous.leftValue;
			right = previous.rightValue;
		}
		Operation *operation = [self newOperation:left previousRight:right];
		[o addObject:operation]; 
	}
	return o;
}

- (NSString *) getOperator {
	return @"x";
}

-(NSInteger) getRandomLeftNumber {
	return -1;
}

-(NSInteger) getRandomRightNumber {
	return -1;
}
-(BOOL) isRandom {
	return TRUE;
}

- (Operation *) newOperation: (NSInteger)previousLeft  previousRight:(NSInteger)previousRight {
	NSInteger left = previousLeft+1;
	NSInteger right = previousRight;
	
	//full random 
	if([self isRandom]) {
		left  = [self getRandomLeftNumber];
		right = [self getRandomRightNumber];
	} else if(left > 10 || right == 0) { //change table
		left = 1;
		right = [self getNextNumberInPreference:right+1];
	} 
	NSString * op = [self getOperator];
	return [Operation newOperation:op left:left right:right];
}

-(NSInteger) getNextNumberInPreference:(NSInteger) start {
	for (int i=start; i<10; i++) {
		if([[NSUserDefaults standardUserDefaults] boolForKey:[[NSNumber numberWithInt:i] stringValue]]) {
			return i;
		}
	}
	return -1;
}

-(NSInteger) getNbSelectedNumber {
	NSInteger count = 0;
	for (int i=1; i<10; i++) {
		if([[NSUserDefaults standardUserDefaults] boolForKey:[[NSNumber numberWithInt:i] stringValue]]) {
			count++;
		}
	}
	return count;
}

-(NSInteger) getValidRandomNumber {
	NSInteger random = 0;
	do {
		random = [self getRandomNumber];
	} while(![self isValidNumber:random]);
	return random;
}

-(NSInteger) getRandomNumber {
	return (NSInteger)rand()% 10;
}

-(BOOL) isValidNumber:(NSInteger)num {
	return [[NSUserDefaults standardUserDefaults] boolForKey:[[NSNumber numberWithInt:num] stringValue]];
}
@end
